﻿using System.Collections.Generic;
using System.Linq;

namespace Kratos.Framework.Infrastructures
{
    public interface IPage
    {
        int RecordCount { get; set; }
        int CurrentPageIndex { get; set; }
        int PageSize { get; set; }
        int NumberOfPages { get; }
        bool IsPreviousPage { get; }
        bool IsNextPage { get; }
    }

    public class PageList<T> : List<T>, IPage
    {
        public PageList(IQueryable<T> source, int pageIndex, int pageSize)
        {
            RecordCount = source.Count();
            CurrentPageIndex = pageIndex;
            PageSize = pageSize;
            AddRange(source.Skip(pageIndex * pageSize).Take(pageSize).ToList());
        }

        public PageList(IEnumerable<T> source, int index, int pageSize)
        {
            RecordCount = source.Count();
            PageSize = pageSize;
            CurrentPageIndex = index;
            AddRange(source.Skip(index * pageSize).Take(pageSize).ToList());
        }

        public int RecordCount
        {
            get;
            set;
        }

        public int CurrentPageIndex
        {
            get;
            set;
        }

        public int PageSize
        {
            get;
            set;
        }

        public int NumberOfPages
        {
            get
            {
                return RecordCount % PageSize == 0 ? RecordCount / PageSize : RecordCount / PageSize + 1;
            }
        }

        public bool IsPreviousPage
        {
            get { return CurrentPageIndex > 0; }
        }

        public bool IsNextPage
        {
            get { return CurrentPageIndex < NumberOfPages - 1; }
        }
    }
}
